package com.zxy.broker.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.common.utils.PageUtils;
import com.zxy.common.utils.Query;

import com.zxy.broker.dao.HousesDao;
import com.zxy.broker.entity.HousesEntity;
import com.zxy.broker.service.HousesService;


@Service("housesService")
public class HousesServiceImpl extends ServiceImpl<HousesDao, HousesEntity> implements HousesService {
    @SuppressWarnings("all")
    @Autowired
    RestHighLevelClient client;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<HousesEntity> wrapper = new QueryWrapper<>();
        String pid = (String) params.get("pid");
        if (pid!=null&&pid!=""){
            int s = Integer.parseInt(pid);
            wrapper.eq("province_id",s);
        }
        String city = (String) params.get("city");
        if (city!=null&&city!=""){
            int s = Integer.parseInt(city);
            wrapper.eq("city_id",s);
        }
        String hname = (String) params.get("hname");
        if (StringUtils.isNotEmpty(hname)){
            wrapper.like("houses_name",hname);
        }
        IPage<HousesEntity> page = this.page(
                new Query<HousesEntity>().getPage(params),
                wrapper
        );


        return new PageUtils(page);
    }

    @Override
    public PageUtils eslist(Map<String, Object> params) {
       try {
           SearchRequest searchRequest = new SearchRequest("houses");
           SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
           BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

           String hname = (String) params.get("hname");
           if (StringUtils.isNotEmpty(hname)){
               boolQueryBuilder.must(QueryBuilders.matchQuery("housesName",hname));
           }
           searchSourceBuilder.query(boolQueryBuilder);
           searchSourceBuilder.aggregation(AggregationBuilders.terms("NAME").field("housesName.keyword"));

           String page = (String) params.get("page");
           String limit = (String) params.get("limit");

           searchSourceBuilder.from((Integer.parseInt(page)-1)*Integer.parseInt(limit));
           searchSourceBuilder.size(Integer.parseInt(limit));
           searchRequest.source(searchSourceBuilder);
           Map<String, Object> map = null;

           SearchResponse searchResponse = null;
           searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
           if (searchResponse.getHits().getTotalHits().value > 0) {
               SearchHit[] searchHit = searchResponse.getHits().getHits();
               for (SearchHit hit : searchHit) {
                   map = hit.getSourceAsMap();
                   System.out.println("map:" + Arrays.toString(map.entrySet().toArray()));
               }
           }

           Aggregations aggregations = searchResponse.getAggregations();
           List<String> list = new ArrayList<String>();
           Terms aggTerms = aggregations.get("NAME");
           List<? extends Terms.Bucket> buckets = aggTerms.getBuckets();
           for (Terms.Bucket bucket : buckets) {
               list.add(bucket.getKeyAsString());
           }
           System.out.println("DISTINCT list values:" + list.toString());


           SearchHits hits = searchResponse.getHits();
           TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
           int numHits = (int) totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
           TotalHits.Relation relation = totalHits.relation;

           SearchHit[] searchHits = hits.getHits();
           ArrayList<HousesEntity> list1 = new ArrayList<>();
           for (SearchHit hit : searchHits) {
               // do something with the SearchHit
               String index = hit.getIndex();
               String id = hit.getId();
               float score = hit.getScore();

               String sourceAsString = hit.getSourceAsString();
               HousesEntity housesEntity = JSON.parseObject(sourceAsString, new TypeReference<HousesEntity>() {
               });
               housesEntity.setId(Long.valueOf(id));
               list1.add(housesEntity);
           }
           return new PageUtils(list1,numHits,Integer.valueOf(limit),Integer.valueOf(page));
       }catch (Exception e){
           e.printStackTrace();
       }
        return null;
    }


}